class_name ObstacleDetector
extends Detector

@export var detect_radius:float = 30
@export_range(1,36) var detect_line_resolution_radio:int = 12
@export_flags_2d_physics var detect_collision_mask:int
var obstacle_closest_point:Array[Vector2] = []
var ray_cast_2ds:Array[RayCast2D] = []

func init_detector(detect_component:DetectComponent):
	super.init_detector(detect_component)
	for i in range(detect_line_resolution_radio):
		var angle = 360.0 / detect_line_resolution_radio
		var ray_cast_2d = RayCast2D.new()
		ray_cast_2d.target_position = Vector2(detect_radius,0)
		ray_cast_2d.collision_mask = detect_collision_mask
		ray_cast_2d.rotate(deg_to_rad(angle) * i)
		ray_cast_2ds.append(ray_cast_2d)
		add_child(ray_cast_2d)
func detect():
	super.detect()
	obstacle_closest_point.clear()
	for ray_cast_2d in ray_cast_2ds:
		ray_cast_2d.force_raycast_update()
		if ray_cast_2d.is_colliding():
			obstacle_closest_point.append(ray_cast_2d.get_collision_point())
func get_closed_point(pos:Vector2) -> Vector2:
	var obstacle_closest_point_copy = obstacle_closest_point.duplicate()
	obstacle_closest_point_copy.sort_custom(func (a:Vector2,b:Vector2):return (a-pos).length() < (b-pos).length())
	return obstacle_closest_point_copy[0] if obstacle_closest_point_copy.size()>0 else Vector2.ZERO

func _init() -> void:
	detector_type = GameEnum.DetectorType.Obstacle
